import React, { Component } from "react";
import {
  NavBar,
  Icon,
  Picker,
  List,
  InputItem,
  Toast,
  TextareaItem,
  Checkbox,
  Button,
  Modal,
  Radio,
} from "antd-mobile";
import { createForm } from "rc-form";
import { district } from "antd-mobile-demo-data"; //ant虚拟省市区
import wxpng from "../assets/imgs/wx.png";
import zfbpng from "../assets/imgs/zfb.png";
import ylpng from "../assets/imgs/yl.png";
import { addAddressHandle, getbuyHandle, getcreateOrderHandle } from "../api";
const CheckboxItem = Checkbox.CheckboxItem;
const RadioItem = Radio.RadioItem;
function closest(el, selector) {
  const matchesSelector =
    el.matches ||
    el.webkitMatchesSelector ||
    el.mozMatchesSelector ||
    el.msMatchesSelector;
  while (el) {
    if (matchesSelector.call(el, selector)) {
      return el;
    }
    el = el.parentElement;
  }
  return null;
}
export class Pay extends Component {
  constructor(props) {
    super(props);
    //{"token":"6bbbc398771c11fac5335574b65fc08145043433","data":{"true_name":"fenggb","city_id":"184","area_id":"2206","area_info":"浙江台州市三门县","address":"城西xxx街道","mob_phone":"15112525173","default":"0"}}
    this.state = {
      totalPrice: "",
      cart_list: "",
      order_sn: "",
      value: 1,
      qrcodeModal: false, // 默认二维码图片的弹框隐藏
      districtArr: [], // 选中之后的地区编码
      // 快递方式数据，通过查看Piker组件的文档的data属性，知道这个属性是一个数组，里面是一个对象，对象中有value和label属性
      expressType: [
        { value: "1", label: "顺丰" },
        { value: "2", label: "圆通" },
        { value: "3", label: "韵达" },
      ],
      selectedExpress: ["1"], // 选中之后的快递编码,默认为顺丰
      goodsAmount: 0, // 商品总额 √
      expressMoment: 0, // 快递费 √
      accept_name: "", // 收货人 √
      address: "", // 收获详细地址 √
      mobile: "", // 收货人电话号码 √
      email: "", // 收货人邮箱地址 √
      post_code: "", // 收货人邮编 √
      payment_id: 6, // 支付方式在线支付, 为默认不可更改 √
      express_id: "1", // 运送方式 1：顺丰  2：圆通 3：韵达（可更改） √√
      message: "", // 订单备注信息 √
      goodsids: "", // 购买商品的id，多个之间用逗号隔开 类似于 '91, 92' 这种格式 √√
      cargoodsobj: "", // 购买商品对象，商品id为key，购买数量为值,类似于{'91': 2, '92': 2}这种格式 √√
      area: {
        province: {
          code: "",
        }, // 省 √√
        city: {
          code: "",
        }, // 市
        area: {
          code: "",
        }, // 区
      },
    };
  }
  componentDidMount() {
    this.getcreateOrderHandle();
  }
  onClose = () => {
    this.setState({
      qrcodeModal: false,
    });
  };
  // 修复ios上页面滚动问题
  onWrapTouchStart = (e) => {
    // fix touch to scroll background page on iOS
    if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
      return;
    }
    const pNode = closest(e.target, ".am-modal-content");
    if (!pNode) {
      e.preventDefault();
    }
  };
  // 创建订单
  getcreateOrderHandle = async () => {
    var createOrder = {
      token:JSON.parse(sessionStorage.getItem("mytoken")),
      address_id: 7,
      cart_id: ["128|1"],
      ifcart: 0,
      pay_message: "",
      share: "",
    };
    let res = await getcreateOrderHandle(createOrder);
    console.log(res, "创建订单");
    // this.state.cart_list = res.data.goods_list;
    // this.state.totalPrice = res.data.goods_total;
    this.setState({
      order_sn: res.data.order_list.order_sn
    })
    // this.state.order_sn = res.data.order_list.order_sn;
    console.log(this.state.order_sn, "order_sn");
    // var num = [];
    // this.cart_list.map( (value, index, array) => {
    //   num = num.concat(+value.goods_num)
    // });
  };
  //立即结算
  immediateSettlement = async () => {

    console.log("立即结算");
    this.setState({
      //隐藏支付弹窗
      qrcodeModal: false,
    });
    var data = {
      token: JSON.parse(sessionStorage.getItem("mytoken")),
      // token: "d9069a2ea653b5b69fd13bdf6fcf081e0b72b8fb",
      data: {
        ordersn: this.state.order_sn, //订单随机数
        type: this.state.value, //支付类型
      },
    };
    let res = await getbuyHandle(data);
    console.log(res, "跳转结算页面");
    if (res.code === 200) {
      window.location.href = res.data.url;
    }
  }

  // 添加地址
 handlePay = async () => {
  this.props.form.validateFields(async (error, value) => {
    if (error) return Toast.fail('请检查数据是否填写正确', 2)
    if (this.state.districtArr.length === 0) return Toast.fail('请选择地区', 2)
    var addressParams = {
      token: JSON.parse(sessionStorage.getItem("mytoken")),
      data: {
        true_name: this.state.accept_name,
        mob_phone: this.state.mobile,
        city_id: "",
        area_id: "",
        area_info:
          this.state.districtArr[0] +
          this.state.districtArr[1] +
          this.state.districtArr[2],
        address: this.state.address,
        default: 0,
      },
    };
    let res = await addAddressHandle(addressParams);
    console.log(res, "保存数据");
    //开启选择支付弹窗
    this.setState({
      qrcodeModal: true,
    });
  });
}
  //选择支付方式单选框
  onChangePay = (value) => {
    this.setState({ value, });
  };
  render() {
    // 先从form属性取出getFieldProps，getFieldError两个属性，这两个属性是两个方法
    const { getFieldProps, getFieldError } = this.props.form;
    const { value } = this.state;
    const payData = [
      { value: 1, label: "支付宝", imgUrl: zfbpng },
      { value: 2, label: "微信", imgUrl: wxpng },
      { value: 3, label: "银联", imgUrl: ylpng },
    ];
    return (
      <div>
        {/* 导航栏 */}
        <NavBar
          mode="dark"
          icon={<Icon type="left" />}
          onLeftClick={() => this.props.history.go(-1)}
        >
          确认下单
        </NavBar>

        {/* 用户下单的表单数据 */}
        <List style={{ backgroundColor: "white" }} className="picker-list">
          {/*
            data用于给Picker提供展示数据
            value用于Picker选中一个数据之后，获取选中的数据
            onChange事件和onOk事件需要把选中的值设置给一个变量
          */}
          <Picker
            extra="请选择(必选)"
            data={district}
            title="地区"
            value={this.state.districtArr}
            onChange={(v) => this.setState({ districtArr: v })}
            onOk={(v) => this.setState({ districtArr: v })}
            onDismiss={(e) => console.log("dismiss", e)}
          >
            <List.Item arrow="horizontal">
              <span style={{ color: "red" }}>*</span>地区
            </List.Item>
          </Picker>
          {/*
            error是一个布尔值，用来展示错误的样式的
            onErrorClick 点击错误图标执行的事件
            利用getFieldProps方法在InputItem组件中自定义需要校验的字段名，然后还要定义它的校验规则
            getFieldProps注意要放在value和onChange之前⭐
            getFieldError在获取错误校验信息时，里面的参数必须和getFieldProps定义的字段名保持一致
            validateTrigger用于设置触发校验的方式
            rules用于设置校验规则
           */}
          <InputItem
            placeholder="收货人详细地址"
            error={getFieldError("myaddress") ? true : false}
            onErrorClick={() => Toast.fail("请输入详细地址！", 2)}
            {...getFieldProps("myaddress", {
              validateTrigger: "onBlur",
              rules: [{ required: true }],
            })}
            onChange={(v) => this.setState({ address: v })}
            value={this.state.address}
          >
            <span style={{ color: "red" }}>*</span>详细地址
          </InputItem>
          <InputItem
            placeholder="收货人姓名"
            error={getFieldError("username") ? true : false}
            onErrorClick={() => Toast.fail("请输入收货人姓名！", 2)}
            {...getFieldProps("username", {
              validateTrigger: "onBlur",
              rules: [{ required: true }],
            })}
            onChange={(v) => this.setState({ accept_name: v })}
            value={this.state.accept_name}
          >
            <span style={{ color: "red" }}>*</span>收货人
          </InputItem>
          <InputItem
            placeholder="收货人手机号"
            error={getFieldError("tel") ? true : false}
            onErrorClick={() => Toast.fail("请输入手机号！", 2)}
            {...getFieldProps("tel", {
              validateTrigger: "onBlur",
              rules: [{ required: true }],
            })}
            onChange={(v) => this.setState({ mobile: v })}
            value={this.state.mobile}
          >
            <span style={{ color: "red" }}>*</span>手机号
          </InputItem>
          <InputItem
            placeholder="收货人邮箱"
            onChange={(v) => this.setState({ email: v })}
            value={this.state.email}
          >
            邮箱
          </InputItem>
          <InputItem
            placeholder="收货人邮编"
            onChange={(v) => this.setState({ post_code: v })}
            value={this.state.post_code}
          >
            邮编
          </InputItem>
          {/* initialValue设置默认值,注意数据类型是一个数组 */}
          <Picker
            extra="请选择(可选)"
            cols={1}
            data={this.state.expressType}
            title="快递方式"
            {...getFieldProps("count", {
              initialValue: ["1"],
            })}
            value={this.state.selectedExpress}
            onChange={(v) => this.setState({ selectedExpress: v })}
            onOk={(v) => this.setState({ selectedExpress: v })}
            onDismiss={(e) => console.log("dismiss", e)}
          >
            <List.Item arrow="horizontal">快递方式</List.Item>
          </Picker>
          {/* rows表示多少行， count表示多少字 */}
          <TextareaItem
            placeholder="备注信息"
            value={this.state.message}
            onChange={(v) => this.setState({ message: v })}
            rows={5}
            count={100}
          ></TextareaItem>
          <CheckboxItem disabled defaultChecked multipleLine>
            在线支付（默认不可更改）
          </CheckboxItem>
          <Button type="primary" onClick={this.handlePay}>
            确认支付
          </Button>
        </List>
        {/* 支付弹框 */}
        <Modal
          popup
          visible={this.state.qrcodeModal}
          onClose={this.onClose}
          animationType="slide-up"
        >
          <List
            renderHeader={() => <div>请选择支付方式</div>}
            className="popup-list"
          >
            <List>
              {payData.map((i) => (
                <RadioItem
                  key={i.value}
                  checked={value === i.value}
                  onChange={() => this.onChangePay(i.value)}
                >
                  <div className="pay-img">
                    <img src={i.imgUrl} alt="" />
                  </div>
                </RadioItem>
              ))}
            </List>
            <List.Item>
              <Button type="primary" onClick={this.immediateSettlement}>
                立即结算
              </Button>
            </List.Item>
          </List>
        </Modal>
        <style jsx>{`
          .my-radio .am-radio {
            padding: 2.5px;
            border: 1px solid #ccc;
            border-radius: 50%;
            margin-right: 5px;
          }
          .pay-img {
            width: 100px;
            height: 50px;
            > img {
              display: block;
              width: 100%;
              height: 100%;
            }
          }
        `}</style>
      </div>
    );
  }
}

export default createForm()(Pay);
